'use client';

import { useState } from 'react';
import { products, categories } from '@/lib/mockData';
import { Product, Category } from '@/lib/types';
import { useApp } from '@/contexts/AppContext';
import { useToast } from '@/components/Toast';

export default function ShopPage() {
  const { dispatch } = useApp();
  const { showToast, ToastContainer } = useToast();
  const [selectedCategory, setSelectedCategory] = useState<string>('all');
  const [sortBy, setSortBy] = useState<string>('default');
  const [priceRange, setPriceRange] = useState<string>('all');

  // 过滤和排序商品
  const filteredProducts = products
    .filter(product => {
      if (selectedCategory === 'all') return true;
      return product.category === selectedCategory;
    })
    .filter(product => {
      if (priceRange === 'all') return true;
      if (priceRange === 'low') return product.price < 50;
      if (priceRange === 'mid') return product.price >= 50 && product.price < 200;
      if (priceRange === 'high') return product.price >= 200;
      return true;
    })
    .sort((a, b) => {
      if (sortBy === 'price-low') return a.price - b.price;
      if (sortBy === 'price-high') return b.price - a.price;
      if (sortBy === 'name') return a.name.localeCompare(b.name);
      return 0;
    });

  const [addingToCart, setAddingToCart] = useState<string | null>(null);
  const [buyingNow, setBuyingNow] = useState<string | null>(null);

  const handleAddToCart = async (product: Product) => {
    setAddingToCart(product.id);
    dispatch({ type: 'ADD_TO_CART', payload: product });
    
    setTimeout(() => {
      setAddingToCart(null);
      showToast(`已将 ${product.name} 加入购物车！`, 'success');
    }, 500);
  };

  const handleBuyNow = async (product: Product) => {
    setBuyingNow(product.id);
    dispatch({ type: 'ADD_TO_CART', payload: product });
    
    setTimeout(() => {
      setBuyingNow(null);
      window.location.href = `/checkout?product=${product.id}`;
    }, 500);
  };

  return (
    <div className="min-h-screen bg-gray-50">
      {/* 页面头部 */}
      <div className="bg-gradient-to-r from-yellow-400 to-orange-400 py-16">
        <div className="max-w-6xl mx-auto px-4 text-center">
          <h1 className="text-4xl font-bold text-black mb-4">盲盒商城</h1>
          <p className="text-xl text-black/80">每一个盒子都是未知的惊喜</p>
        </div>
      </div>

      <div className="max-w-6xl mx-auto px-4 py-8">
        <div className="flex flex-col lg:flex-row gap-8">
          {/* 侧边栏筛选 */}
          <div className="lg:w-64 space-y-6">
            {/* 分类筛选 */}
            <div className="bg-white rounded-lg p-6 shadow-sm">
              <h3 className="font-semibold text-gray-800 mb-4">商品分类</h3>
              <div className="space-y-2">
                <label className="flex items-center space-x-2 cursor-pointer">
                  <input
                    type="radio"
                    name="category"
                    value="all"
                    checked={selectedCategory === 'all'}
                    onChange={(e) => setSelectedCategory(e.target.value)}
                    className="text-orange-500"
                  />
                  <span className="text-gray-700">全部分类</span>
                </label>
                {categories.map((category) => (
                  <label key={category.id} className="flex items-center space-x-2 cursor-pointer">
                    <input
                      type="radio"
                      name="category"
                      value={category.id}
                      checked={selectedCategory === category.id}
                      onChange={(e) => setSelectedCategory(e.target.value)}
                      className="text-orange-500"
                    />
                    <span className="text-gray-700">{category.icon} {category.name}</span>
                  </label>
                ))}
              </div>
            </div>

            {/* 价格筛选 */}
            <div className="bg-white rounded-lg p-6 shadow-sm">
              <h3 className="font-semibold text-gray-800 mb-4">价格区间</h3>
              <div className="space-y-2">
                {[
                  { value: 'all', label: '全部价格' },
                  { value: 'low', label: '50元以下' },
                  { value: 'mid', label: '50-200元' },
                  { value: 'high', label: '200元以上' }
                ].map((option) => (
                  <label key={option.value} className="flex items-center space-x-2 cursor-pointer">
                    <input
                      type="radio"
                      name="price"
                      value={option.value}
                      checked={priceRange === option.value}
                      onChange={(e) => setPriceRange(e.target.value)}
                      className="text-orange-500"
                    />
                    <span className="text-gray-700">{option.label}</span>
                  </label>
                ))}
              </div>
            </div>

            {/* 排序 */}
            <div className="bg-white rounded-lg p-6 shadow-sm">
              <h3 className="font-semibold text-gray-800 mb-4">排序方式</h3>
              <select
                value={sortBy}
                onChange={(e) => setSortBy(e.target.value)}
                className="w-full p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-transparent"
              >
                <option value="default">默认排序</option>
                <option value="price-low">价格从低到高</option>
                <option value="price-high">价格从高到低</option>
                <option value="name">按名称排序</option>
              </select>
            </div>
          </div>

          {/* 商品列表 */}
          <div className="flex-1">
            <div className="mb-6 flex justify-between items-center">
              <p className="text-gray-600">
                共找到 <span className="font-semibold text-gray-800">{filteredProducts.length}</span> 个商品
              </p>
            </div>

            <div className="grid md:grid-cols-2 xl:grid-cols-3 gap-6">
              {filteredProducts.map((product) => (
                <div
                  key={product.id}
                  className="bg-white rounded-lg shadow-sm hover:shadow-lg transition-shadow overflow-hidden group"
                >
                  <div className={`h-48 bg-gradient-to-br ${product.bgColor} flex items-center justify-center relative`}>
                    <div className="w-24 h-24 bg-yellow-400 rounded-lg flex items-center justify-center shadow-xl group-hover:scale-110 transition-transform">
                      <span className="text-3xl">📦</span>
                    </div>
                    <div className="absolute top-3 right-3 bg-black/20 text-white px-2 py-1 rounded text-xs">
                      库存: {product.stock}
                    </div>
                  </div>
                  
                  <div className="p-4">
                    <div className="flex items-center justify-between mb-2">
                      <span className="bg-gray-600 text-white px-2 py-1 rounded text-xs font-bold">
                        盲盒
                      </span>
                      <div className="text-2xl font-bold text-gray-800">
                        ¥{product.price}
                      </div>
                    </div>
                    
                    <h3 className="font-semibold text-lg text-gray-900 mb-2">
                      {product.name}
                    </h3>
                    
                    <p className="text-sm text-gray-600 mb-2">
                      估值: {product.originalValue}
                    </p>
                    
                    <p className="text-sm text-gray-600 mb-4 line-clamp-2">
                      {product.description}
                    </p>
                    
                    {product.probability && (
                      <p className="text-xs text-orange-600 mb-4 font-medium">
                        {product.probability}
                      </p>
                    )}
                    
                    <div className="space-y-3">
                      <a
                        href={`/product/${product.id}`}
                        className="w-full block bg-gray-50 text-gray-700 py-3 px-4 rounded-lg text-center hover:bg-gray-100 transition-colors font-medium border border-gray-200"
                      >
                        🔍 查看详情
                      </a>
                      <div className="grid grid-cols-2 gap-2">
                        <button
                          onClick={() => handleAddToCart(product)}
                          disabled={addingToCart === product.id}
                          className="border-2 border-orange-500 text-orange-600 font-medium py-2.5 px-3 rounded-lg hover:bg-orange-50 transition-colors disabled:opacity-50 disabled:cursor-not-allowed text-sm"
                        >
                          {addingToCart === product.id ? '添加中...' : '🛒 加入购物车'}
                        </button>
                        <button
                          onClick={() => handleBuyNow(product)}
                          disabled={buyingNow === product.id}
                          className="bg-gradient-to-r from-yellow-400 to-orange-400 text-black font-bold py-2.5 px-3 rounded-lg hover:shadow-lg transition-shadow disabled:opacity-50 disabled:cursor-not-allowed text-sm"
                        >
                          {buyingNow === product.id ? '处理中...' : '⚡ 立即购买'}
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>

            {filteredProducts.length === 0 && (
              <div className="text-center py-12">
                <div className="text-6xl mb-4">📦</div>
                <h3 className="text-xl font-semibold text-gray-800 mb-2">暂无商品</h3>
                <p className="text-gray-600">请尝试调整筛选条件</p>
              </div>
            )}
          </div>
        </div>
      </div>
      <ToastContainer />
    </div>
  );
}